#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/3 16:57
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : common.py
# @Software: PyCharm
# @Desc    :
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/21 0:09
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : common.py
# @Software: PyCharm
# @Desc    :
from django.db.models import Q
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from common.models import Account
from common.sers.ser_login import LoginSerializer
from common.utils.encrypt import md5
from common.utils.token import create_token


class LoginView(GenericAPIView):
    serializer_class = LoginSerializer
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        username = serializer.validated_data['username']
        username_phone = serializer.validated_data['username']
        password = serializer.validated_data['password']
        obj_user = Account.objects.filter(is_delete=0, pt_flag=0).all()
        obj_user = obj_user.filter(Q(username=username) | Q(mobile=username_phone), password=md5(password)).first()

        if not obj_user:
            return Response({'code': 10000, "msg": "用户名或者密码错误"})
        if obj_user.status == 0:
            return Response({'code': 10001, "msg": "账号已经被禁用，请联系管理员"})
        user_info = {"id": obj_user.id, "phone": obj_user.mobile, "username": obj_user.username}
        token_data = {"id": obj_user.id, "phone": obj_user.mobile, "username": obj_user.username,
                      "user_info": user_info}
        token = create_token(token_data)
        return Response({'code': 200, "token": token, "msg": "登录成功", "user_info": user_info})


class CheckToken(GenericAPIView):

    def get(self, request, *args, **kwargs):
        return Response({'code': 200})
